#!/usr/bin/env python
'''markdown2creole: simple markdown to creole converter
converts small subset of markdown - no quotes, no code blocks,
no nested lists.

© Dmitri dmych Brechalov, 2011
'''
import re
try:
    from hashlib import md5
except:
    from md5 import md5

def convertFonts(line):
    hash = '<md5-%s>' % md5('**').hexdigest()
    boldrepl = hash + r'\2' + hash 
    line = re.sub(r"(?<!\w)(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1(?!\w)", boldrepl, line)
    line = re.sub(r"(?<!\w)(\*|_)(?=\S)(.+?)(?<=\S)\1(?!\w)", r'//\2//', line)
    line = line.replace(hash, '**')
    return line

def convertLists(line):
    line = re.sub(r'^[-+*]( .*|$)', r'*\1', line)
    line = re.sub(r'^[0-9]+\.( .*|$)', r'#\1', line)
    return line

def convertLinks(line):
    line = re.sub(r'!\[([^]]*)\]\(([^)]+)\)', r'{{\2|\1}}', line)
    line = re.sub(r'\[([^]]+)\]\(([^)]+)\)', r'[[\2|\1]]', line)
    return line

def convertLine(line, prev):
    skip = False
    if re.match('^=+ *$', line):
        skip = True
        line = '= %s =\n' % prev.strip()
    elif re.match('^-+ *$', line) and prev.strip():
        skip = True
        line = '== %s ==\n' % prev.strip()
    elif re.match('^#+.*', line):
        for i in range(6,0,-1):
            pattern = '^'+'#'*i+'(.*)$'
            repl = '=' * i + '\\1' + '=' * i
            line = re.sub(pattern, repl, line)
    else:
        line = convertFonts(line)
        line = convertLists(line)
        line = convertLinks(line)
    return line, skip

def m2c(ifd, ofd):
    prevline = None
    for line in ifd.readlines():
        line, skip = convertLine(line, prevline)
        if not skip and prevline is not None:
            ofd.write(prevline)
            print prevline,
        prevline = line
    if not skip and prevline is not None:
        ofd.write(prevline)
        print prevline,
    return None

def markdown2creole(ifn, ofn):
    try:
        ifd = open(ifn, "r")
    except IOError:
        return 'Cannot find file %s' % ifn
    try:
        ofd = open(ofn, "w")
    except IOError:
        return 'Cannot open file %s' % ofn
    return m2c(ifd, ofd)

if __name__ == '__main__':
    dirname = '/sdcard/m2ctest'
    ifname = dirname + '.mdt'
    ofname = dirname + '.txt'
    print ifname, '->', ofname
    err = markdown2creole(ifname, ofname)
    if err is None:
        print 'All done'
    else:
        print err
